# -*- coding:utf-8 -*-
# @File    : apiMethod.py
# *************************

import math, datetime, hashlib, requests, json
from comm.unit.cacheData import *
from urllib3.exceptions import InsecureRequestWarning
from config import *

evn = RC["run_evn"]
def getAuth(func):
    # 装饰器，如果已生成了鉴权，下次就不用再次生成鉴权，减少鉴权对性能的影响
    def warpper():
        myauth = cache.get("the_auth")
        if myauth == None:
            auth = func()
            cache.set("the_auth",auth)
            return auth
        else:
            return myauth
    return warpper


def creat_cookies(evn='test'):
    if evn == 'test':
        login_url = 'https://test-mt.myscrm.com.cn/api/index.php?r=site/login&kfs=fangzhiadmin_test'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded', "Accept": "application/json"
        }
        data = {
            "usercode": "dengh01@mingyuanyun.com",
            "password": "F5012750@#$", #运行demo请补充帐号密码
            "code": "",
            "verfcode": ""
        }
    elif evn == 'hw':
        login_url = 'https://test-mt.myscrm.com.cn/api/index.php?r=site/login&orgcode=znfangcadmin&kfs=znfangcadmin'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded', "Accept": "application/json"
        }
        data = {
            "usercode": "dengh01@mingyuanyun.com",
            "password": "F5012750@#$",  # 运行demo请补充帐号密码
            "code": "",
            "verfcode": ""
        }
    else:
        login_url = 'https://mt.myscrm.com.cn/api/index.php?r=site/login&kfs=yktyadmin'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded', "Accept": "application/json"
        }
        data = {
            # "usercode": "public",
            # "password": "mysoft123",  # 运行demo请补充帐号密码
            "usercode": "dengh01@mingyuanyun.com",
            "password": "F5012750@#$",  # 运行demo请补充帐号密码
            "code": "",
            "verfcode": ""
        }
    l = requests.post(login_url, data=data, headers=headers, verify=False)
    # print("ll::",l.text)

    session = requests.Session()
    cookie_jar = session.post(login_url, data=data, headers=headers, verify=False).cookies
    cookie = requests.utils.dict_from_cookiejar(cookie_jar)
    # print("cookie:",cookie)
    return cookie


@getAuth
def create_headers():
    '''
    :return: 返回测试环境headers
    '''

    evn="test"
    cookies = creat_cookies(evn)
    if evn == "test":
        acw_tc = cookies['acw_tc']
        test_myscrm_phpsessid = cookies['test_myscrm_phpsessid']
        # print("cookies:",cookies)
        headers = {
            "Cookie": "__tracker_user_id__=25672d841703f80-31b800297d-46656947; test_env_orgcode=fangzhiadmin_test; cms_org_code=fangzhiadmin_test; ad_analysis_user_guid=1d849080-ba35-11ec-a5b8-7cd30aeb066e; ad_analysis_user_code=myyk_400_mysoftadmin; __fast_sid__=256f8d79ae3f4e0-0eae0099e1-3e695470; acw_tc={}; test_myscrm_phpsessid={}; env_orgcode=fangzhiadmin_test".format(
                acw_tc, test_myscrm_phpsessid),
            "Cookie": "__tracker_user_id__=2585099bf0cce80-c3a8008105-f636324d; prod_env_orgcode=yktyadmin; test_env_orgcode=fangzhiadmin_test; "
                      "cms_userCode=myyk_400_mysoftadmin; env_orgcode=fangzhiadmin_test; test_myscrm_phpsessid={}; "
                      "cms_org_code=fangzhiadmin_test; cms_user_guid=1d849080-ba35-11ec-a5b8-7cd30aeb066e; "
                      "__fast_sid__=258792f5edd95c0-2adc00ada8-b9303535; "
                      "acw_tc={}".format(test_myscrm_phpsessid,acw_tc),
            "Origin": "https://test-mt.myscrm.com.cn",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
        }
        return headers
    else:
        acw_tc = cookies['acw_tc']
        # cg_myscrm_phpsessid = cookies['cg_myscrm_phpsessid']
        aliyungf_tc = cookies['aliyungf_tc']
        last_env = cookies['last_env']
        # print("cookies:",cookies)
        headers = {
            "Cookie": "__secdyid=49e9dcd3eaf9581654973cda8be7f283705faf924706c52e021661504225; _uab_collina=168595104115726833568748; __tracker_user_id__=25672d841703f80-31b800297d-46656947; test_env_orgcode=fangzhiadmin_test; prod_env_orgcode=yktyadmin; ad_analysis_user_guid=39ee14cf-2f93-1473-1713-022dd1c4ca21; ad_analysis_user_code=public; cms_org_code=yktyadmin; bffAuthorization=Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2d1aWQiOiIzOWVlMTRjZi0yZjkzLTE0NzMtMTcxMy0wMjJkZDFjNGNhMjEiLCJvcmdfY29kZSI6InlrdHlhZG1pbiIsImlhdCI6MTY4NzM0MzUxNSwiZXhwIjoxNjg3OTQ4MzE1fQ.y4ed3RXpQYMFbOjauVsUl4pHRvA7t_7lZ9VKolWaNC8; __fast_sid__=25795c08add95c0-2adc00f781-9741486f; aliyungf_tc={}; acw_tc={}; last_env={}; env_orgcode=yktyadmin".format(
                aliyungf_tc,acw_tc,last_env),


            "Origin": "https://mt.myscrm.com.cn",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
        }

        headers = {'Cookie': '__tracker_user_id__=2585accef43cda0-117a00fd52-d6202e69; '
                            'aliyungf_tc=c442d6d21ccee6904c4c30a4add740f8c723280a637a7ddcac41943bf739db3d; is_mysoft_admin=0; test_env_orgcode=fangzhiadmin_test; intelligence_orgcode=yxdcyxzsadmin; '
                            'intelligence_orgcode.sig=XZngLxVf4qtt9Lb4DfgMpvsliVc; env_orgcode.sig=0C384VEnpi6A25P6ruo5bwo_3IE; __DATA_INTELLIGENCE_TOKEN__=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXNzaW9uX2lkIjoiajEzdjQyNWhqZnYwa2VzdXJ1bzFtMWg5bDQiLCJ5a191c2VyX2NvZGUiOiJteXlrXzQwMF9teXNvZnRhZG1pbiIsInlrX29yZ19jb2RlIjoieXhkY3l4enNhZG1pbiIsInlrX3Rva2VuIjoibnVsbCIsImlhdCI6MTY5MjY4OTQ5NywiZXhwIjoxNjkyNzAwMjk3fQ.byoU3lDag-Gf3-7fvu05XbKDS6QTq7v6MKtpj_SHjM8; __DATA_INTELLIGENCE_TOKEN__.sig=3v4F3hKpHs1Wq3lHV4TVJbS4W10; cms_user_guid=1d849080-ba35-11ec-a5b8-7cd30aeb066e; env_orgcode=yktyadmin; prod_env_orgcode=yktyadmin; last_env=g1; __fast_sid__=2596e76b186c4e0-ebae00e960-314d3631; acw_tc=707c9f6b16929251909178874e0d169511d15a69cd1fd20caaec2b598a77d0; cg_myscrm_phpsessid=uadqc9r789ef46ak3ar3k74uh7; bffAuthorization=Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2d1aWQiOiIxZDg0OTA4MC1iYTM1LTExZWMtYTViOC03Y2QzMGFlYjA2NmUiLCJvcmdfY29kZSI6InlrdHlhZG1pbiIsImlhdCI6MTY5MjkyNTIyMiwiZXhwIjoxNjkzNTMwMDIyfQ.6qLXFroRTB4YdQczCfrldL_9zMvB_F_A_Y3UJKMMz5w; '
                            'cms_org_code=yktyadmin; cms_userCode=myyk_400_mysoftadmin'}

        return headers


def create_cehuaheaders():
    '''
    :return: 登录策划账号查看授权归属权限
    '''

    evn="test"
    # login_url = 'https://test-qmyxcg.myscrm.com.cn/api/index.php?r=site/login&kfs=fangzhiadmin_test'
    login_url = 'https://test-mt.myscrm.com.cn/api/index.php?r=site/login&orgcode=fangzhiadmin_test&kfs=fangzhiadmin_test&version=2'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded', "Accept": "application/json"
    }
    data = {
        "usercode": "邓恢测试账号",#"videoAutoTest",
        "password": "yk123456",  # 运行demo请补充帐号密码
        "code": "",
        "verfcode": ""
    }
    # l = requests.post(login_url, data=data, headers=headers, verify=False)
    # print("ll::",l.text)

    session = requests.Session()
    h = session.post(login_url, data=data, headers=headers, verify=False).headers
    print("h",type(h),h.get('Set-Cookie'))
    print(h)

    setCookie = str(h.get('Set-Cookie'))


    if evn == "test":

        # print("cookies:",cookies)
        # headers = {
        #     "Cookie": "__tracker_user_id__=25672d841703f80-31b800297d-46656947; test_env_orgcode=fangzhiadmin_test; cms_org_code=fangzhiadmin_test; ad_analysis_user_guid=1d849080-ba35-11ec-a5b8-7cd30aeb066e; ad_analysis_user_code=myyk_400_mysoftadmin; __fast_sid__=256f8d79ae3f4e0-0eae0099e1-3e695470; acw_tc={}; test_myscrm_phpsessid={}; env_orgcode=fangzhiadmin_test".format(
        #         acw_tc, test_myscrm_phpsessid),
        #     "Cookie": "__tracker_user_id__=2585099bf0cce80-c3a8008105-f636324d; prod_env_orgcode=yktyadmin; test_env_orgcode=fangzhiadmin_test; "
        #               "cms_userCode=myyk_400_mysoftadmin; env_orgcode=fangzhiadmin_test; test_myscrm_phpsessid={}; "
        #               "cms_org_code=fangzhiadmin_test; cms_user_guid=1d849080-ba35-11ec-a5b8-7cd30aeb066e; "
        #               "__fast_sid__=258792f5edd95c0-2adc00ada8-b9303535; "
        #               "acw_tc={}".format(test_myscrm_phpsessid,acw_tc),
        #     "Origin": "https://test-qmyxcg.myscrm.com.cn",
        #     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
        # }
        headers = {
            "Cookie": "__tracker_user_id__=2585099bf0cce80-c3a8008105-f636324d; prod_env_orgcode=yktyadmin; test_env_orgcode=fangzhiadmin_test; "
                      "cms_userCode=myyk_400_mysoftadmin; env_orgcode=fangzhiadmin_test; "
                      "cms_org_code=fangzhiadmin_test; cms_user_guid=1d849080-ba35-11ec-a5b8-7cd30aeb066e; test_myscrm_phpsessid=d1nsfjbuh80noedd0j5jq27f13;"
                      "__fast_sid__=258792f5edd95c0-2adc00ada8-b9303535;{}".format(setCookie),
            "Origin": "https://test-qmyxcg.myscrm.com.cn",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
        }
        print("headers::",headers)
        return headers


@getAuth
def create_headers_hw():
    '''
    :return: 返回测试环境headers
    '''
    cookies = creat_cookies('hw')
    acw_tc = cookies['acw_tc']
    test_myscrm_phpsessid = cookies['test_myscrm_phpsessid']
    # print("cookies:",cookies)
    headers = {
        # "Cookie": "__tracker_user_id__=25672d841703f80-31b800297d-46656947; test_env_orgcode=fangzhiadmin_test; cms_org_code=fangzhiadmin_test; ad_analysis_user_guid=1d849080-ba35-11ec-a5b8-7cd30aeb066e; ad_analysis_user_code=myyk_400_mysoftadmin; __fast_sid__=256f8d79ae3f4e0-0eae0099e1-3e695470; acw_tc={}; test_myscrm_phpsessid={}; env_orgcode=fangzhiadmin_test".format(
        #     acw_tc, test_myscrm_phpsessid),
        "Cookie": "__tracker_user_id__=266126bf3d117c0-30fc002132-4e206870; __fast_sid__=266126bf3d1db00-fbf00015cb-29282e69; "
                  "test_myscrm_phpsessid={}; env_orgcode=znfangcadmin; test_env_orgcode=znfangcadmin;"
                  " acw_tc={}; is_workbench=1;"
                  " cms_org_code=znfangcadmin; cms_user_guid=1d849080-ba35-11ec-a5b8-7cd30aeb066e; cms_userCode=myyk_400_mysoftadmin; "
                  "bffAuthorization=Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2d1aWQiOiIxZDg0OTA4MC1iYTM1LTExZWMtYTViOC03Y2QzMGFlYjA2NmUiLCJvcmdfY29kZSI6InpuZmFuZ2NhZG1pbiIsImlhdCI6MTcyODQ1OTA0OSwiZXhwIjoxNzI5MDYzODQ5fQ.egR42bzOwEPU5rIqfG1lU8kmY1iiJdWmPgtdfHbNAk0".format(test_myscrm_phpsessid,acw_tc),
        "Origin": "https://test-mt.myscrm.com.cn",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    }
    return headers


def sync_header():
    header = {"Grpc-Metadata-user_guid":"3a07fd8f-f4b9-83c9-a421-f5586c512b65",
              "Grpc-Metadata-orgcode":"fangzhiadmin_test"}
    # token = header
    # cache.set('fenyu.yaml',token)
    #不用return
    return header


def  create_mobile_cookies():
    '''
    :return:
    '''
    login_url = 'https://test-advisor.myscrm.cn/ad-serving-bff/user/login'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded', "Accept": "application/json"
    }
    data = {
        "id": "17512018904",
        "passwd": "a580445a257e173db2fcb94288084377"
    }

    session = requests.Session()
    cookie_jar = session.post(login_url, data=data, headers=headers, verify=False).cookies
    cookie = requests.utils.dict_from_cookiejar(cookie_jar)

    headers = {
        "Cookie": "acw_tc={}; cms_org_code=fangzhiadmin_test; cms_user_guid=39cadbad-0966-80b1-edc0-1994f96f78ec;".format(
            cookie["acw_tc"])
    }
    return headers


@getAuth
def creat_jd_test_header():
    """
    创建金地测试环境的登录header
    """
    login_url = "https://osaletest.gemdale.com/gyx-admin-web/user/login"
    data = {
        "pwdEnc": "emhhbmd5YW84",
        "userCode": "zhangyao8"
    }
    headers = {
        "content-type": "application/json",
        "Accept": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
    }
    res = requests.post(url=login_url, json=data, headers=headers, verify=False)
    res = json.loads(res.text)
    sessId = res["data"]["sessId"]
    headers = {
        "Content-Type": "application/json",
        "Cookie": "env_orgcode=jdjituanadmin_test;cms_userCode=zhangyao8;cms_user_guid=3a02c7e6-cc86-180a-3fb6-4220380035a6;test_myscrm_phpsessid={}".format(
            sessId)
    }
    return headers


def distributeHeader():
    headers = {
        "Grpc-Metadata-user_code":"testdata",
        "Grpc-Metadata-user_guid": "testdata",
        "Grpc-Metadata-orgcode":"fangzhiadmin_test"
    }
    return headers


def appTestInfo(orgCode):
    """
    :return: 获客app待测试的手机号和租户号
    """
    mobile_tel = "18188888888"
    return mobile_tel,orgCode

@getAuth
def appNativeHeader():
    """
    :return: 获取获取app原生界面接口header
    """
    # 获取登录cookie
    if evn == 'test':
        mobile_tel,orgCode = appTestInfo('fangzhiadmin_test')
    elif evn == 'HW':
        mobile_tel,orgCode = appTestInfo('znfangcadmin')
    else:
        mobile_tel, orgCode = appTestInfo('fangzhiadmin_test')
    sms_login = 'https://test-qmyxcg.myscrm.com.cn/v1-bff-ad-serving-bff/vapp/app/verifySMS'
    data = {"data": {"mobile_tel": mobile_tel, "code": "999999"}}  # 测试环境的手机和验证码
    print(("data",data))
    response = requests.post(sms_login, json=data, verify=False)
    # print("cookie:",cookie.cookies)
    # setCookie = cookie[0]
    setCookie = response.headers.get("Set-Cookie")

    headers = {
        "Cookie": "acw_tc={}".format(setCookie),
        "orgcode": orgCode,
        "grpc-metadata-orgcode": orgCode
    }
    print(headers)
    return headers


@getAuth
def appWebHeader():
    """
    :return: 获取获取app网页界面接口header
    """
    if evn == 'test':
        mobile_tel, orgCode = appTestInfo('fangzhiadmin_test')
    elif evn == 'HW':
        mobile_tel, orgCode = appTestInfo('znfangcadmin')
    else:
        mobile_tel, orgCode = appTestInfo('fangzhiadmin_test')
    headers = appNativeHeader()
    # orgCode = 'fangzhiadmin_test'
    # 根据获取到的cookie请求APP接口相关业务数据(域名为https://test-qmyxcg.myscrm.com.cn的接口)
    orgcodeUrl = 'https://test-qmyxcg.myscrm.com.cn/v1-bff-ad-serving-bff/vapp/app/getMultiPlatformUserOrgcodeList'
    orgCodeData = {"data": {"mobile": mobile_tel}}  # 测试环境登录的手机
    orgResult = requests.post(orgcodeUrl, json=orgCodeData, headers=headers, verify=False)
    accountData = json.loads(orgResult.text)
    vt_multi_user_id = accountData["data"]["vt_multi_user_id"]
    # 根据cookie获取到登录token
    userPhoneLogin = 'https://test-qmyxcg.myscrm.com.cn/v1-bff-ad-serving-bff/vapp/app/userPhoneLogin'
    userData = {"data": {"vt_multi_user_id": vt_multi_user_id, "orgcode": orgCode},"orgcode": orgCode} # 指定租户
    userDataResult = requests.post(userPhoneLogin, json=userData, headers=headers, verify=False)
    userDataJason = json.loads(userDataResult.text)
    token = userDataJason['data']['token']
    # print(userDataResult.text)

    # 获取到token后请求网页的相关业务数据（域名为https://test-advisor.myscrm.cn的接口）
    dataheaders = {
        "authorization": '{}'.format(token),
        "orgcode": orgCode,
        "grpc-metadata-orgcode": orgCode
    }
    return dataheaders




def getThirdUserId(platform):
    """
    :param platform:
    :return: 编辑移动用户管理获取第三方ID
    """
    url = "http://gateway-test-inner.myscrm.cn/video-core/v1/account/list"

    payload = json.dumps({
        "platform_type": platform,
        "need_multi_platform_account": True
    })
    headers = {
        'Grpc-Metadata-orgcode': 'fangzhiadmin_test',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    jsonData = json.loads(response.text)
    accountList = jsonData['list']
    for dic in accountList:
        if not dic.get("has_multi_platform_account"):
            vc_account_id = dic["vc_account_id"]
    return vc_account_id

print(appWebHeader)

